#include <rtthread.h>
#include "./watchdog.h"
#include "../HALayer/stm32_gpio.hpp"
#include "../parameter.h"

static GPIO_Class watchdog(GPIOC, GPIO_Pin_0); /* 看门狗 */
static void Watchdog_Thread(void *parameter);  /* 看门狗喂狗线程 */
static struct rt_thread watchdog_thread;       /* 看门狗线程句柄 */
ALIGN(RT_ALIGN_SIZE)                           /* 线程栈4字节对齐 */
static char watchdog_thread_stack[160];        /* 线程栈起始地址 */

static GPIO_Class watchdog_enable(GPIOC, GPIO_Pin_1); /* 看门狗使能引脚 */

void watchdog_thread_init(void)
{
    rt_err_t rt_result;
    watchdog.Init(GPIO_Mode_OUT); /* 端口为输出模式 */
    watchdog.Set();
    if (agv_parameter->wtd_enable_flag)
    {
        /* 使能看门狗 */
        watchdog_enable.Init(GPIO_Mode_OUT);
        watchdog_enable.Set(); /* 使能引脚 */
    }
    rt_result = rt_thread_init(&watchdog_thread, "watchdog thread", Watchdog_Thread, RT_NULL, watchdog_thread_stack, sizeof(watchdog_thread_stack), 15, 1);
    if (rt_result == RT_EOK)
    {
        rt_thread_startup(&watchdog_thread); /* 启动线程 */
    }
    else
    {
        rt_kprintf("watchdog thread error\n");
    }
}

void Watchdog_Thread(void *parameter)
{
    while (1)
    {
        watchdog.Set();
        rt_thread_delay(50);
        watchdog.Clear();
        rt_thread_delay(50);
    }
}
